﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MillerApp.DataContract;
using MillerApp.DataContract.Common;
using MillerApp.CommonLib.Utility;
using MillerApp.DataContract.MillerDB;
using MillerApp.DataAccess.MillerDB;
using System.Text.RegularExpressions;
using System.Threading;
using MillerApp.DataContract.Common.Entity;

namespace MillerApp.Business.Stock
{
    public class SecurityService
    {
        public SecurityService()
        {
            //this.IsAutoEvent = false;
        }

        public static void GetAStockInfo()
        {
            //沪市A股资金流向
            string url2 = "http://vol.stock.hexun.com/Now/Industry/Info_3.ashx?code=Z02";
            //[['截止2012年08月31日15：01，沪市A股全部成交中，资金流入性成交<span style=color:red>1726521.21</span>万元，资金流出性成交<span style=color:green>-1704025.05</span>万元，不确定性成交87591.11万元，流入流出成交差额<span style=color:red>22496.16</span>万元，占沪市A股全部成交0.64%。'],['2012年08月31日 15:01']]

            //深市A股资金流向
            string url3 = "http://vol.stock.hexun.com/Now/Industry/Info_3.ashx?code=Z03";
            //[['截止2012年08月31日15：01，深市A股全部成交中，资金流入性成交<span style=color:red>1456066.91</span>万元，资金流出性成交<span style=color:green>-1434593.35</span>万元，不确定性成交141575.87万元，流入流出成交差额<span style=color:red>21473.56</span>万元，占深市A股全部成交0.71%。'],['2012年08月31日 15:01']]

            //  全市场资金流向
            string url = "http://vol.stock.hexun.com/Now/Index/Info_3.ashx";
            //[['截止2012年08月31日15：01，全市场综合总成交777.63亿元，其中:<br/>沪深A股共成交739.94亿元，沪市A股成交351.81亿元，深市A股(包含中小企业板)成交303.22亿元，创业板成交84.90亿元，A股成交中，资金流入性成交<span style=color:red>358.86</span>亿元，资金流出性成交<span style=color:green>-353.02</span>亿元，不确定性成交28.06亿元，流入流出成交差额<span style=color:red>5.84</span>亿元，占大盘全部成交0.75%。<br/>沪市B股总成交0.14亿元，流入流出成交差额<span style=color:red>0.01</span>亿元(美元)。<br/>深市B股总成交2.06亿元，流入流出成交差额<span style=color:red>0.12</span>亿元(港币)。<br/>两市基金总成交35.50亿元，流入流出成交差额<span style=color:red>1.38</span>亿元，占大盘全部成交0.18%。<br/>两市权证总成交0.00亿元，流入流出成交差额<span style=color:green>--</span>亿元，占大盘全部成交--%。'],['2012年08月31日 15:01']]

            // 创业板资金流向
            string url4 = "http://vol.stock.hexun.com/Now/Industry/Info_3.ashx?code=Z12";
            //[['截止2012年08月31日15：01，创业板全部成交中，资金流入性成交<span style=color:red>406235.95</span>万元，资金流出性成交<span style=color:green>-391496.97</span>万元，不确定性成交51285.90万元，流入流出成交差额<span style=color:red>14738.98</span>万元，占创业板全部成交1.74%。'],['2012年08月31日 15:01']]

            HttpWebRequestHelper client = new HttpWebRequestHelper();
            RequestData rdata = new RequestData();
            string content = client.Request(url, rdata, true);
            // [['截止2012年08月31日15：01，全市场综合总成交777.63亿元，
            //其中:<br/>沪深A股共成交739.94亿元，沪市A股成交351.81亿元，
            //深市A股(包含中小企业板)成交303.22亿元，
            //创业板成交84.90亿元，A股成交中，资金流入性成交<span style=color:red>358.89</span>亿元，资金流出性成交<span style=color:green>-353.00</span>亿元，不确定性成交28.04亿元，流入流出成交差额<span style=color:red>5.89</span>亿元，占大盘全部成交0.76%。<br/>沪市B股总成交0.14亿元，流入流出成交差额<span style=color:red>0.01</span>亿元(美元)。<br/>深市B股总成交2.06亿元，流入流出成交差额<span style=color:red>0.12</span>亿元(港币)。<br/>两市基金总成交35.50亿元，流入流出成交差额<span style=color:red>1.38</span>亿元，占大盘全部成交0.18%。<br/>两市权证总成交0.00亿元，流入流出成交差额<span style=color:green>--</span>亿元，占大盘全部成交--%。'],['2012年08月31日 15:01']]
            //string content = "";
            //沪市A股成交：
            //深市A股(包含中小企业板))成交
            //创业板成交
            //流入：
            //流出
            //不确定性成交
            //差额
            return;

        }

        #region 同步股票信息
        public void AutoUpdateSecurities(object args)
        {
            DelegateMessageHanldler method = null;
            if (args is DelegateMessageHanldler)
            {
                method = args as DelegateMessageHanldler;
            }

            //获取所有证券列表
            int recordCount = 0;
            List<SecurityEntity> securities = SecurityManager.GetSecuritysByCond(string.Empty, string.Empty, 0, int.MaxValue, out recordCount);

            Dictionary<string, object> msgs = new Dictionary<string, object>();
            msgs.Add("message", "开始获取沪市(上海交易所)的股票信息....");
            method(msgs);

            //<li><a href="stock.php?code=sh600257" target="_blank">大湖股份(600257)</a></li>
            //匹配沪市
            string url = "http://ustock.finance.ifeng.com/stock_list.php?type=sh";
            HttpWebRequestHelper client = new HttpWebRequestHelper();
            client.TextEncoding = Encoding.UTF8;
            RequestData rdata = new RequestData();
            string content = client.Request(url, rdata, true);
            UpdateSecurities("sh", content, ref securities, method);
            msgs = new Dictionary<string, object>();
            msgs.Add("message", "成功获取沪市(上海交易所)的股票信息!");
            method(msgs);
            Thread.Sleep(200);

            //深市
            msgs = new Dictionary<string, object>();
            msgs.Add("message", "开始获取深市(深圳交易所)的股票信息....");
            method(msgs);
            content = string.Empty;
            url = "http://ustock.finance.ifeng.com/stock_list.php?type=sz";
            content = client.Request(url, rdata, true);
            UpdateSecurities("sz", content, ref securities, method);
            msgs = new Dictionary<string, object>();
            msgs.Add("message", "成功获取深市(深圳交易所)的股票信息!");
            method(msgs);
            Thread.Sleep(200);

            //创业板
            msgs = new Dictionary<string, object>();
            msgs.Add("message", "开始获取创业板的股票信息....");
            method(msgs);
            content = string.Empty;
            url = "http://ustock.finance.ifeng.com/stock_list.php?type=gem";
            content = client.Request(url, rdata, true);
            UpdateSecurities("sz", content, ref securities, method);
            msgs = new Dictionary<string, object>();
            msgs.Add("message", "成功获取创业板股票信息!");
            method(msgs);
            //Thread.Sleep(200);


            msgs = new Dictionary<string, object>();
            msgs.Add("FINISHED", "成功同步所有股票信息!");
            method(msgs);

            //MessageBox.Show("成功同步所有股票信息");
        }

        private void UpdateSecurities(string stockexchangecode, string content, ref List<SecurityEntity> securities, DelegateMessageHanldler method)
        {
            string pattern = ">[^0-9]{1,9}[(][0-9]{6}[)]</a>";
            MatchCollection matches = Regex.Matches(content, pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
            char[] splitChar = { '(' };
            foreach (Match item in matches)
            {
                string itemVal = item.Value.Replace("</a>", string.Empty).Replace(">", string.Empty).Replace(")", string.Empty);//>浦发银行(600000)</a>
                string[] vals = itemVal.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);
                if (vals.Length == 2)
                {
                    string secShortName = vals[0];
                    string secCode = vals[1];
                    var a = from b in securities
                            where b.seccode.Trim() == secCode.Trim()
                            select b;
                    if (a != null && a.Count<SecurityEntity>() > 0)//更新
                    {
                        SecurityEntity selectEntity = a.First<SecurityEntity>();
                        if (selectEntity.secshortname != secShortName)
                        {
                            selectEntity.secshortname = secShortName;
                            List<string> ts = null;
                            selectEntity.pysx = StringHelper.GetAcronyms(secShortName, out ts);
                            SecurityManager.UpdateSecurity(selectEntity);
                            if (method != null)
                            {
                                Dictionary<string, object> args = new Dictionary<string, object>();
                                args.Add("message", "证券" + secCode + "的证券简称发生变化已更新....");
                                method(args);
                            }
                        }
                    }
                    else
                    {
                        if (secCode == "002999")
                        {
                            continue;
                        }
                        SecurityEntity selectEntity = new SecurityEntity();
                        selectEntity.seccode = secCode.Trim();
                        selectEntity.compcode = secCode.Trim();
                        selectEntity.stockexchangecode = stockexchangecode;
                        selectEntity.secshortname = secShortName.Trim();
                        selectEntity.status = 1;
                        List<string> ts = null;
                        selectEntity.pysx = StringHelper.GetAcronyms(secShortName, out ts);
                        SecurityManager.InsertSecurity(selectEntity);
                        securities.Add(selectEntity);
                        if (method != null)
                        {
                            Dictionary<string, object> args = new Dictionary<string, object>();
                            args.Add("message", "发现新证券" + secCode + "，已存储...");
                            method(args);
                        }
                    }
                }
            }
        }
        #endregion 同步股票信息

        #region 获取股票交易行情信息
        /// <summary>
        /// 所有的证券列表
        /// Key为深沪市(深市传sz,沪市传sh)，Value为证券代码
        /// </summary>
        public List<KeyValueEntry> ALLSecCodeList { get; set; }

        ///// <summary>
        ///// 是否是自动事件
        ///// </summary>
        //public bool IsAutoEvent { get; set; }

        /// <summary>
        /// 自动获取行情信息
        /// </summary>
        /// <param name="args"></param>
        public void AutoGetSecuritiesHQXX(object args)
        {
            try
            {
                DelegateMessageHanldler method = null;
                if (args is DelegateMessageHanldler)
                {
                    method = args as DelegateMessageHanldler;
                }
                else
                {
                    return;
                }

                if (ALLSecCodeList == null || ALLSecCodeList.Count <= 0)
                {
                    return;
                }
                Dictionary<string, object> msgs = new Dictionary<string, object>();
                msgs.Add("message", "正在获取股票交易行情信息....");
                method(msgs);

                int step = 40;//默认是40个证券请求一次Web获取数据
                CommonHelper helper = new CommonHelper();
                string requestMaxStr = helper.GetAppSettingConfig("RequestMax");
                int.TryParse(requestMaxStr, out step);

                int i = ALLSecCodeList.Count / step;
                if (ALLSecCodeList.Count % step != 0)
                {
                    i++;
                }

                List<KeyValueEntry> selectedItem = new List<KeyValueEntry>();
                List<KeyValueEntry> selectedItem2 = new List<KeyValueEntry>();
                int t = 0;
                foreach (var item in ALLSecCodeList)
                {
                    selectedItem.Add(item);
                    if (selectedItem.Count == step)
                    {
                        this.GetStockData(selectedItem);
                        selectedItem2.AddRange(selectedItem);
                        selectedItem = new List<KeyValueEntry>();
                        t++;
                        decimal vs = (t * 100 / i);
                        string strvs = string.Format("{0:N0}", vs) + "%";
                        msgs = new Dictionary<string, object>();
                        msgs.Add("message", "已获取" + strvs + "的交易行情数据....");
                        method(msgs);
                    }
                }
                if (selectedItem.Count > 0)
                {
                    this.GetStockData(selectedItem);
                    selectedItem2.AddRange(selectedItem);
                    selectedItem = new List<KeyValueEntry>();
                    msgs = new Dictionary<string, object>();
                    msgs.Add("FINISHED", "已获取" + "100%" + "的交易行情数据....");
                    method(msgs);
                }
                //MessageBox.Show("成功获取股票交易行情数据");
            }
            catch (Exception ex)
            {
                //MessageBox.Show("获取股票交易行情数据出现异常，详细信息请看日志！");
                //LogService.WriteLog("获取股票交易行情数据出现异常:[Message]" + ex.Message + "[StackTrace]" + ex.StackTrace);
            }
        }

        #region 通过各网站接口获取股票交易行情基本信息
        /// <summary>
        /// 通过各网站接口获取股票交易行情基本信息
        /// </summary>
        /// <param name="secCodeList">股票代码列表</param>
        private void GetStockData(List<KeyValueEntry> secCodeList)
        {
            //1.拼接URL请求路径
            Random rand = new System.Random();
            double randValue = rand.NextDouble();

            char[] endChar = { ',' };
            string postData = string.Empty;
            string postData2 = string.Empty;
            foreach (var item in secCodeList)
            {
                postData += item.Key + item.Value + ",";
                postData2 += "ff_" + item.Key + item.Value + ",";
            }
            postData = postData.TrimEnd(endChar);
            postData2 = postData2.TrimEnd(endChar);

            //2.接口说明：
            //通过新浪接口获取股票交易行情基本信息
            //通过新浪的接口获取股票涨幅和换手率
            //通过腾讯QQ的接口获取资金流向  http://qt.gtimg.cn/r=0.83152117749519&q=ff_sz002024,ff_sz002409
            string url = @"http://hq.sinajs.cn/list=" + postData;
            string url2 = @"http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/MoneyFlow.ssi_ssfx_flzjtj?daima=" + postData;
            string url3 = @"http://qt.gtimg.cn/r=" + randValue.ToString() + "&q=" + postData2;

            HttpWebRequestHelper client = new HttpWebRequestHelper();
            RequestData rdata = new RequestData();

            client.TextEncoding = Encoding.Default;
            string content = client.Request(url, rdata, true);
            string content2 = client.Request(url2, rdata, true);
            string content3 = client.Request(url3, rdata, true);

            List<StockItemInfo> infos = this.GetWebStockInfos(secCodeList, content);
            UpdateWebStockChangeratioAndTurnover(content2, ref infos);
            UpdateWebStockMoneyFlowInfos(content3, ref infos);

            //更新至数据库中
            SaveWebStockInfos2DataBase(ref infos);
        }

        #region 通过新浪接口获取股票交易行情基本信息
        /// <summary>
        /// 通过新浪接口获取股票交易行情基本信息
        /// </summary>
        /// <param name="secCodeList">股票列表</param>
        /// <param name="contents">通过新浪接口获取股票交易行情基本信息集[字符串]</param>
        /// <returns>拆分的结构化数据</returns>
        private List<StockItemInfo> GetWebStockInfos(List<KeyValueEntry> secCodeList, string contents)
        {
            List<StockItemInfo> infos = new List<StockItemInfo>();
            string[] splitStrings = { ";" };
            string[] contentItems = contents.Split(splitStrings, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in secCodeList)
            {
                string secCode = item.Value;
                var a = from b in contentItems
                        where b.IndexOf(item.Value + "=") >= 0
                        select b;
                if (a != null && a.Count<string>() > 0)
                {
                    string itemContents = a.First<string>();
                    StockItemInfo itemInfo = GetWebStockInfo(secCode, itemContents);
                    if (itemInfo != null)
                    {
                        infos.Add(itemInfo);
                    }
                }
            }
            return infos;
        }
        /// <summary>
        /// 通过新浪接口获取股票交易行情基本信息(单只股票)
        /// </summary>
        /// <param name="secCode">股票代码</param>
        /// <param name="itemContents">通过新浪接口获取股票交易行情基本信息集</param>
        /// <returns>拆分的结构化数据</returns>
        private StockItemInfo GetWebStockInfo(string secCode, string itemContents)
        {
            StockItemInfo info = new StockItemInfo();
            int i = itemContents.IndexOf("\"");
            int j = itemContents.LastIndexOf("\"");

            char[] splitChar = { ',' };
            string[] items = itemContents.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);

            if ((j - i) <= 5)
            {
                if (items.Length < 30)
                {
                    return null;
                }
            }
            else
            {
                string itemValues = itemContents.Substring(i + 1, j - i - 1);
                items = itemValues.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);
            }

            info.ZQDM = secCode;
            info.ZQMC = items[0];
            info.JRRQ = items[30];
            info.JRKP = items[1];
            info.ZRSP = items[2];
            info.JRSP = items[3];
            info.JRZG = items[4];
            info.JRZD = items[5];
            info.JBuyJG = items[6];
            info.JSellJG = items[7];
            info.CJSL = items[8];
            info.CJJE = items[9];
            info.JRSJ = items[31];

            info.M1SL = items[10];
            info.M1JG = items[11];

            info.M2SL = items[12];
            info.M2JG = items[13];

            info.M3SL = items[14];
            info.M3JG = items[15];

            info.M4SL = items[16];
            info.M4JG = items[17];

            info.M5SL = items[18];
            info.M5JG = items[19];

            info.M1SL2 = items[20];
            info.M1JG2 = items[21];

            info.M2SL2 = items[22];
            info.M2JG2 = items[23];

            info.M3SL2 = items[24];
            info.M3JG2 = items[25];

            info.M4SL2 = items[26];
            info.M4JG2 = items[27];

            info.M5SL2 = items[28];
            info.M5JG2 = items[29];

            return info;

            //0：”大秦铁路”，股票名字；
            //1：”27.55″，今日开盘价；
            //2：”27.25″，昨日收盘价；
            //3：”26.91″，当前价格；
            //4：”27.55″，今日最高价；
            //5：”26.20″，今日最低价；
            //6：”26.91″，竞买价，即“买一”报价；
            //7：”26.92″，竞卖价，即“卖一”报价；
            //8：”22114263″，成交的股票数，由于股票交易以一百股为基本单位，所以在使用时，通常把该值除以一百；
            //9：”589824680″，成交金额，单位为“元”，为了一目了然，通常以“万元”为成交金额的单位，所以通常把该值除以一万；
            //10：”4695″，“买一”申请4695股，即47手；
            //11：”26.91″，“买一”报价；
            //12：”57590″，“买二”
            //13：”26.90″，“买二”
            //14：”14700″，“买三”
            //15：”26.89″，“买三”
            //16：”14300″，“买四”
            //17：”26.88″，“买四”
            //18：”15100″，“买五”
            //19：”26.87″，“买五”
            //20：”3100″，“卖一”申报3100股，即31手；
            //21：”26.92″，“卖一”报价
            //(22, 23), (24, 25), (26,27), (28, 29)分别为“卖二”至“卖四的情况”
            //30：”2008-01-11″，日期；
            //31：”15:05:32″，时间；
        }
        #endregion 通过新浪接口获取股票交易行情基本信息

        #region 通过新浪的接口获取股票涨幅和换手率
        /// <summary>
        /// 通过新浪的接口获取股票涨幅和换手率
        /// </summary>
        /// <param name="contents">获取的字符串</param>
        /// <param name="infos">股票行情数据</param>
        private void UpdateWebStockChangeratioAndTurnover(string contents, ref List<StockItemInfo> infos)
        {
            char[] spitChars = { '{', '}' };
            char[] spitChars1 = { ',' };
            char[] spitChars2 = { ':' };
            contents = contents.Replace("[", string.Empty).Replace("]", string.Empty);
            string[] itemValues = contents.Split(spitChars, StringSplitOptions.RemoveEmptyEntries);

            foreach (var item in infos)
            {
                string secCode = item.ZQDM;
                foreach (var item2 in itemValues)
                {
                    //changeratio:"0.00487805",volume:"101107392.0000",turnover:"185.957"
                    if (item2.IndexOf(secCode) > 0)
                    {
                        string[] itemValue2 = item2.Split(spitChars1, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var item3 in itemValue2)
                        {
                            string[] itemValue3 = item3.Split(spitChars2, StringSplitOptions.RemoveEmptyEntries);
                            if (itemValue3.Length == 2)
                            {
                                if (itemValue3[0].ToLower() == "changeratio")
                                {
                                    item.ZDF = itemValue3[1].Replace("\"", string.Empty);
                                }
                                else if (itemValue3[0].ToLower() == "turnover")
                                {
                                    item.HSL = itemValue3[1].Replace("\"", string.Empty); ;
                                }
                            }
                        }
                    }
                }
            }
        }
        #endregion 通过新浪的接口获取股票涨幅和换手率

        #region 通过腾讯QQ的接口获取资金流向
        /// <summary>
        /// 通过腾讯QQ的接口获取资金流向
        /// </summary>
        /// <param name="contents">获取的字符串</param>
        /// <param name="infos">股票行情信息</param>
        private void UpdateWebStockMoneyFlowInfos(string contents, ref List<StockItemInfo> infos)
        {
            //v_ff_sz002024="sz002024~23818.75~17390.75~6428.00~10.39~8285.07~12353.76~-4068.69~-6.58~61848.32~30418.17~23886.34~苏宁电器~20120820";
            //0:证券代码（其他）
            //1:资金流入(主力)
            //2:资金流出(主力)
            //3:资金流入/出合计(主力)
            //4:资金流入/流出比例差（主力）

            //5:资金流入(散户)
            //6:资金流出(散户)
            //7:资金流入/出合计(散户)
            //8:资金流入/流出比例差（散户）

            //9.流入流出资金总数（散户出入+主力出入）

            //v_ff_sz002409 = "sz002409~39.88~41.00~-1.12~-0.37~86.00~138.06~-52.06~-17.07~304.95~107.82~117.74~雅克科技~20120820";
            char[] spitChars = { ';' };
            char[] spitChars1 = { '~' };
            string[] itemValues = contents.Split(spitChars, StringSplitOptions.RemoveEmptyEntries);

            foreach (var item in infos)
            {
                string secCode = item.ZQDM;
                foreach (var item2 in itemValues)
                {
                    //changeratio:"0.00487805",volume:"101107392.0000",turnover:"185.957"
                    if (item2.IndexOf(secCode) > 0)
                    {
                        string[] itemValue2 = item2.Split(spitChars1, StringSplitOptions.RemoveEmptyEntries);
                        if (itemValue2.Length > 9)
                        {
                            item.ZJLRZL = itemValue2[1];
                            item.ZJLCZL = itemValue2[2];
                            item.ZJHJZL = itemValue2[3];
                            item.ZJBLCZL = itemValue2[4];

                            item.ZJLRSH = itemValue2[5];
                            item.ZJLCSH = itemValue2[6];
                            item.ZJHJSH = itemValue2[7];
                            item.ZJBLCSH = itemValue2[8];

                            item.ZJZSALL = itemValue2[9];
                        }
                    }
                }
            }
        }
        #endregion 通过腾讯QQ的接口获取资金流向

        #region 保存股票交易行情数据到数据库中
        /// <summary>
        /// 保存股票交易行情数据到数据库中[millerdb->Stockquotations]
        /// </summary>
        /// <param name="stockInfos">股票交易行情数据</param>
        private void SaveWebStockInfos2DataBase(ref List<StockItemInfo> stockInfos)
        {
            foreach (var item in stockInfos)
            {
                StockquotationsEntity entity = new StockquotationsEntity();
                entity.seccode = item.ZQDM;
                DateTime tradeDay = DateTime.Now.Date;
                if (DateTime.TryParse(item.JRRQ, out tradeDay) == false)
                {
                    continue;
                }
                entity.tradeday = tradeDay;
                entity.todayopeningprice = GetDecimalValue(item.JRKP);
                entity.yesterdayclosingprice = GetDecimalValue(item.ZRSP);
                entity.todayclosingprice = GetDecimalValue(item.JRSP);
                entity.todayhighestprice = GetDecimalValue(item.JRZG);
                entity.todaylowestprice = GetDecimalValue(item.JRZD);
                entity.tradingvolume = GetDecimalValue(item.CJSL);
                entity.tradingmoneyvolume = GetDecimalValue(item.CJJE);

                entity.competitiveprice = GetDecimalValue(item.JBuyJG);
                entity.reserveprice = GetDecimalValue(item.JSellJG);

                entity.buyingvolume1 = GetDecimalValue(item.M1SL);
                entity.buyingvolume2 = GetDecimalValue(item.M2SL);
                entity.buyingvolume3 = GetDecimalValue(item.M3SL);
                entity.buyingvolume4 = GetDecimalValue(item.M4SL);
                entity.buyingvolume5 = GetDecimalValue(item.M5SL);

                entity.buyingprice1 = GetDecimalValue(item.M1JG);
                entity.buyingprice2 = GetDecimalValue(item.M2JG);
                entity.buyingprice3 = GetDecimalValue(item.M3JG);
                entity.buyingprice4 = GetDecimalValue(item.M4JG);
                entity.buyingprice5 = GetDecimalValue(item.M5JG);

                entity.sellingvolume1 = GetDecimalValue(item.M1SL2);
                entity.sellingvolume2 = GetDecimalValue(item.M2SL2);
                entity.sellingvolume3 = GetDecimalValue(item.M3SL2);
                entity.sellingvolume4 = GetDecimalValue(item.M4SL2);
                entity.sellingvolume5 = GetDecimalValue(item.M5SL2);

                entity.sellingprice1 = GetDecimalValue(item.M1JG2);
                entity.sellingprice2 = GetDecimalValue(item.M2JG2);
                entity.sellingprice3 = GetDecimalValue(item.M3JG2);
                entity.sellingprice4 = GetDecimalValue(item.M4JG2);
                entity.sellingprice5 = GetDecimalValue(item.M5JG2);

                entity.turnoverrate = GetDecimalValue(item.HSL);
                entity.changeratio = GetDecimalValue(item.ZDF);

                entity.inflowmain = GetDecimalValue(item.ZJLRZL);
                entity.outflowmain = GetDecimalValue(item.ZJLCZL);

                entity.inflowretail = GetDecimalValue(item.ZJLRSH);
                entity.outflowretail = GetDecimalValue(item.ZJLCSH);

                entity.createtime = DateTime.Now;
                entity.modifytime = DateTime.Now;

                StockquotationsManager.InsertStockquotations(entity);

                //if (IsAutoEvent == false)
                //{
                //}
                //else
                //{
                //    StockquotationsManager.InsertStockquotations2(entity);
                //}
            }
        }
        /// <summary>
        /// 字符串转换成数字
        /// </summary>
        /// <param name="strVal"></param>
        /// <returns></returns>
        private decimal GetDecimalValue(string strVal)
        {
            decimal d = 0;
            decimal.TryParse(strVal, out d);
            return d;
        }
        private int GetIntValue(string strVal)
        {
            int d = 0;
            int.TryParse(strVal, out d);
            return d;
        }
        #endregion 保存股票交易行情数据到数据库中
        #endregion 通过各网站接口获取股票交易行情基本信息

        /// <summary>
        /// 股票行情信息
        /// </summary>
        public class StockItemInfo
        {
            public string ZQDM { get; set; }
            public string ZQMC { get; set; }
            public string JRRQ { get; set; }
            public string JRKP { get; set; }
            public string ZRSP { get; set; }
            public string JRSP { get; set; }

            public string JRZG { get; set; }
            public string JRZD { get; set; }

            public string CJSL { get; set; }
            public string CJJE { get; set; }

            public string JBuyJG { get; set; }
            public string JSellJG { get; set; }
            public string JRSJ { get; set; }

            public string M1SL { get; set; }
            public string M1JG { get; set; }
            public string M2SL { get; set; }
            public string M2JG { get; set; }
            public string M3SL { get; set; }
            public string M3JG { get; set; }
            public string M4SL { get; set; }
            public string M4JG { get; set; }
            public string M5SL { get; set; }
            public string M5JG { get; set; }

            public string M1SL2 { get; set; }
            public string M1JG2 { get; set; }
            public string M2SL2 { get; set; }
            public string M2JG2 { get; set; }
            public string M3SL2 { get; set; }
            public string M3JG2 { get; set; }
            public string M4SL2 { get; set; }
            public string M4JG2 { get; set; }
            public string M5SL2 { get; set; }
            public string M5JG2 { get; set; }

            /// <summary>
            /// 换手率
            /// </summary>
            public string HSL { get; set; }
            /// <summary>
            /// 涨跌幅
            /// </summary>
            public string ZDF { get; set; }


            //1:
            /// <summary>
            /// 资金流入(主力)
            /// </summary>
            public string ZJLRZL { get; set; }
            //2:
            /// <summary>
            /// 资金流出(主力)
            /// </summary>
            public string ZJLCZL { get; set; }
            //3:
            /// <summary>
            /// 资金流入/出合计(主力)
            /// </summary>
            public string ZJHJZL { get; set; }
            //4:
            /// <summary>
            /// 资金流入/流出比例差（主力）
            /// </summary>
            public string ZJBLCZL { get; set; }

            //5:
            /// <summary>
            /// 资金流入(散户)
            /// </summary>
            public string ZJLRSH { get; set; }
            //6:
            /// <summary>
            /// 资金流出(散户)
            /// </summary>
            public string ZJLCSH { get; set; }
            //7:
            /// <summary>
            /// 资金流入/出合计(散户)
            /// </summary>
            public string ZJHJSH { get; set; }
            //8:
            /// <summary>
            /// 资金流入/流出比例差（散户）
            /// </summary>
            public string ZJBLCSH { get; set; }

            //9.
            /// <summary>
            /// 流入流出资金总数（散户出入+主力出入）
            /// </summary>
            public string ZJZSALL { get; set; }
        }

        #endregion 获取股票交易行情信息

        #region 获取资金流向信息
        /// <summary>
        /// 根据交易日期获取股市资金流向
        /// </summary>
        /// <param name="datetime">交易日期</param>
        private List<FundflowEntity> AutoGetInOrOutflows(DateTime datetime)
        {
            string datetimeparam = datetime.ToString("yyyy-MM-dd");
            string url = @"http://vol.stock.hexun.com/Data/MarketOverview.ashx?date=" + datetimeparam + "&count=20&page=1&callback=hxbase_json2";

            HttpWebRequestHelper client = new HttpWebRequestHelper();
            RequestData rdata = new RequestData();

            client.TextEncoding = Encoding.Default;
            string content = client.Request(url, rdata, true);

            List<FundflowEntity> list = GetFundflows(content, datetime);
            return list;
        }

        /// <summary>
        /// 根据抓取的网络数据转化成格式化的数据
        /// </summary>
        /// <param name="webContents">网络抓取的字符串</param>
        /// <returns></returns>
        private List<FundflowEntity> GetFundflows(string webContents, DateTime date)
        {
            int i = 1;
            string pattern = "{StockName:[^}]*}";
            MatchCollection matches = Regex.Matches(webContents, pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
            List<FundflowEntity> resultList = new List<FundflowEntity>();
            foreach (Match item in matches)
            {
                FundflowEntity entity = new FundflowEntity();
                entity.tradeday = date.Date;
                string result = item.ToString();
                //Console.Write(i.ToString() + ":   ");
                //Console.WriteLine(result);

                int findex = result.IndexOf("'");
                int sindex = result.IndexOf("'", findex + 1);
                string marketName = result.Substring(findex + 1, sindex - findex - 1);

                findex = result.IndexOf("FundsDay");
                findex = result.IndexOf("'", findex);
                sindex = result.IndexOf("'", findex + 1);
                string seriesdaysStr = result.Substring(findex + 1, sindex - findex - 1);
                entity.seriesdays = GetIntValue(seriesdaysStr);

                string pattern2 = "<span[^>]*>-?\\d*\\.?\\d*%?</span>";
                MatchCollection matches2 = Regex.Matches(result, pattern2, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);

                entity.itemcode = marketName;//市场

                if (matches2.Count == 4)
                {
                    //资金流入(万元)
                    entity.inflow = GetDecimalValue2(matches2[0].ToString());
                    //资金流出(万元)
                    entity.outflow = GetDecimalValue2(matches2[1].ToString());
                    //资金净流入(万元)
                    entity.netflow = GetDecimalValue2(matches2[2].ToString());
                    //资金净流入率
                    entity.inflowpfr = GetDecimalValue2(matches2[3].ToString().Replace("%", "")) / 100;
                }

                string pattern3 = ">\\d*</a>";
                MatchCollection matches3 = Regex.Matches(result, pattern3, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);

                if (matches3.Count == 2)
                {
                    string itemcount = matches3[0].ToString().Replace("</a>", "").Replace(">", "");
                    string itemcount2 = matches3[1].ToString().Replace("</a>", "").Replace(">", "");
                    //资金流入股票数量(只)
                    entity.inflowstockscount = GetIntValue(itemcount);

                    //资金流出股票数量(只)
                    entity.outflowstockscount = GetIntValue(itemcount2);
                }
                resultList.Add(entity);
                i++;
            }
            return resultList;
        }

        private decimal GetDecimalValue2(string str)
        {
            decimal d = 0;
            int findex = str.IndexOf(">");
            int sindex = str.IndexOf("</span>");
            string s = str.Substring(findex + 1, sindex - findex - 1);
            d = GetDecimalValue(s);
            return d;
        }

        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        /// <summary>
        /// 获取资金流
        /// </summary>
        public void AutoGetInOrOutflows(object args)
        {
            Dictionary<string, object> msgs = new Dictionary<string, object>();
            DelegateMessageHanldler method = null;
            if (args is DelegateMessageHanldler)
            {
                method = args as DelegateMessageHanldler;
            }
            else
            {
                return;
            }
            List<FundflowEntity> list = new List<FundflowEntity>();
            int date = (EndDate - StartDate).Days;
            for (int i = 0; i < date + 1; i++)
            {
                DateTime dtCalc = StartDate.AddDays(i);
                if (dtCalc.DayOfWeek == DayOfWeek.Saturday || dtCalc.DayOfWeek == DayOfWeek.Sunday)
                {
                    continue;
                }
                try
                {
                    List<FundflowEntity> listTemp = AutoGetInOrOutflows(dtCalc);
                    list.AddRange(listTemp);
                }
                catch (Exception ex)
                {
                    
                }
                msgs = new Dictionary<string, object>();
                msgs.Add("message", "已获取" + dtCalc.ToString("yyyy-MM-dd") + "的资金流向数据....");
                method(msgs);
            }
            FundflowManager.DeleteFundFlowsByDateTime(StartDate, EndDate);
            foreach (var item in list)
            {
                FundflowManager.InsertFundflow(item);
            }
        }

        #endregion 获取资金流向信息

        /// <summary>
        /// 获取所有的证券信息
        /// </summary>
        /// <returns></returns>
        public static List<SecurityEntity> GetAllSecurities()
        {
            int recordCount = 0;
            List<SecurityEntity> list = SecurityManager.GetSecuritysByCond(string.Empty, string.Empty, 0, int.MaxValue, out recordCount);
            if (list == null || list.Count <= 0)
            {
                return null;
            }
            return list;
        }

    }
}
